#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# cron: 30 22 * * *
# new Env("快手任务每日统计")
import os
import re
import json
import glob
import datetime
import requests
from collections import defaultdict

# ====================== 配置区域 ======================
LOG_DIR_PATTERN = "/ql/data/log/XiaoMao_ksjs_pro_*"
DEBUG_MODE = True
REPORT_FILE = "/ql/data/log/Message/PUSH_kuaishou.log"
HISTORY_FILE = "/ql/data/log/Message/PUSH_kuaishou.json"
CASH_WARNING_THRESHOLD = 15.0
EGG_WARNING_THRESHOLD = 72
PUSH_PLUS_TOKEN = "your_pushplus_token_here"  # 替换为您的PushPlus token
# =====================================================

def pushplus_send(title, content):
    """通过PushPlus发送通知"""
    if not PUSH_PLUS_TOKEN or PUSH_PLUS_TOKEN == "your_pushplus_token_here":
        print("⚠️ PushPlus token未配置，跳过消息发送")
        return None
    
    url = "http://www.pushplus.plus/send"
    headers = {"Content-Type": "application/json"}
    data = {
        "token": PUSH_PLUS_TOKEN,
        "title": title,
        "content": content,
        "template": "txt"
    }
    
    try:
        response = requests.post(url, json=data, headers=headers, timeout=10)
        if response.status_code == 200:
            result = response.json()
            if result.get("code") == 200:
                print(f"✅ PushPlus消息发送成功，消息ID: {result.get('data')}")
                return result.get("data")
            else:
                print(f"❌ PushPlus消息发送失败: {result.get('msg')}")
        else:
            print(f"❌ PushPlus请求失败，状态码: {response.status_code}")
    except Exception as e:
        print(f"❌ PushPlus发送异常: {str(e)}")
    
    return None

def parse_log_file(file_path):
    """解析日志文件，提取账号信息"""
    accounts = {}
    current_account = None
    file_date = os.path.basename(file_path)[:10]  # 从文件名获取日期
    
    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            
            # 检测新账号区块
            account_match = re.match(r'------------\[(.*?)\]------------', line)
            if account_match:
                account_name = account_match.group(1)
                current_account = {
                    'name': account_name,
                    'coins': None,
                    'cash': None,
                    'eggs': None,
                    'feed': None,
                    'lottery_count': 0,
                    'wheel_balance': 0.0,
                    'warnings': [],
                    'coin_increment': 0,  # 今日金币增加量
                    'date': file_date,
                    'file': os.path.basename(file_path)  # 记录文件名
                }
                accounts[account_name] = current_account
                continue
            
            if not current_account:
                continue
            
            # 解析账号基本信息
            if current_account['coins'] is None:
                coins_match = re.search(r'账号【\d+】\[\d+\] 【([\d.]+)】金币【(\d+)】', line)
                if coins_match:
                    try:
                        current_account['cash'] = float(coins_match.group(1))
                        current_account['coins'] = int(coins_match.group(2))
                    except ValueError:
                        pass
                    continue
            
            # 解析鸭蛋数量
            eggs_match = re.search(r'鸭蛋数量【(\d+)】', line)
            if eggs_match:
                try:
                    current_account['eggs'] = int(eggs_match.group(1))
                except ValueError:
                    pass
            
            # 解析饲料数量
            feed_match = re.search(r'剩余饲料【(\d+)】', line)
            if feed_match:
                try:
                    current_account['feed'] = int(feed_match.group(1))
                except ValueError:
                    pass
            
            # 解析抽奖次数
            lottery_match = re.search(r'实物抽奖次数【(\d+)】', line)
            if lottery_match:
                try:
                    current_account['lottery_count'] = int(lottery_match.group(1))
                except ValueError:
                    pass
            
            # 解析转盘余额
            wheel_match = re.search(r'现金转盘余额【([\d.]+)】元', line)
            if wheel_match:
                try:
                    current_account['wheel_balance'] = float(wheel_match.group(1))
                except ValueError:
                    pass
            
            # 检测警告信息
            if '⚠️⚠️快手打卡还有其他任务没做' in line:
                current_account['warnings'].append('快手打卡任务未完成')
            
            # 检测金币增加量（开宝箱）
            coin_inc_match = re.search(r'开宝箱奖励已到账获得(\d+)金币', line)
            if coin_inc_match:
                try:
                    current_account['coin_increment'] += int(coin_inc_match.group(1))
                except ValueError:
                    pass
            
            # 检测其他金币奖励
            other_coin_match = re.search(r'获得(\d+)金币', line)
            if other_coin_match and "开宝箱" not in line:
                try:
                    current_account['coin_increment'] += int(other_coin_match.group(1))
                except ValueError:
                    pass
    
    return accounts

def calculate_withdrawal(prev_data, current_data):
    """计算提现金额（使用昨日数据）"""
    withdrawal = 0.0
    for account_name, account in current_data.items():
        prev_account = prev_data.get(account_name, {})
        prev_cash = prev_account.get('cash', 0.0)
        prev_coins = prev_account.get('coins', 0)
        current_cash = account.get('cash', 0.0)
        
        # 计算预期提现金额
        expected_conversion = prev_coins / 10000
        calculated_withdrawal = prev_cash + expected_conversion - current_cash
        
        # 只处理正值提现
        if calculated_withdrawal > 0:
            # 应用容差 (0.3)
            if abs(calculated_withdrawal - round(calculated_withdrawal)) <= 0.3:
                withdrawal += round(calculated_withdrawal)
            else:
                # 处理0.5元提现的情况
                if 0.2 <= calculated_withdrawal <= 0.8:
                    withdrawal += 0.5
                else:
                    withdrawal += round(calculated_withdrawal)
    
    return max(0, withdrawal)  # 确保提现金额不为负

def get_account_coin_increment(account_name, prev_coins, current_coins):
    """计算金币增加量（更智能的方法）"""
    # 如果金币增加量小于0，可能是数据错误，重新计算
    if prev_coins > 0 and current_coins > prev_coins:
        return current_coins - prev_coins
    return 0

def generate_report(today_accounts, prev_data, report_date):
    """生成报告内容"""
    # 全局统计
    total_accounts = len(today_accounts)
    total_coins = sum(acc.get('coins', 0) for acc in today_accounts.values())
    total_eggs = sum(acc.get('eggs', 0) for acc in today_accounts.values())
    total_feed = sum(acc.get('feed', 0) for acc in today_accounts.values())
    total_lottery_count = sum(acc.get('lottery_count', 0) for acc in today_accounts.values())
    total_wheel_balance = sum(acc.get('wheel_balance', 0.0) for acc in today_accounts.values())
    
    # 计算总金币增加量（基于昨日数据）
    total_coin_increment = 0
    for acc_name, acc_data in today_accounts.items():
        prev_acc = prev_data.get(acc_name, {})
        prev_coins = prev_acc.get('coins', 0)
        current_coins = acc_data.get('coins', 0)
        total_coin_increment += get_account_coin_increment(acc_name, prev_coins, current_coins)
    
    total_cash = sum(acc.get('cash', 0.0) for acc in today_accounts.values())
    
    # 计算提现金额
    withdrawal = calculate_withdrawal(prev_data, today_accounts)
    
    # 警告汇总
    cash_warnings = []
    egg_warnings = []
    task_warnings = defaultdict(list)
    
    for acc in today_accounts.values():
        cash = acc.get('cash', 0.0)
        eggs = acc.get('eggs', 0)
        
        if cash >= CASH_WARNING_THRESHOLD:
            cash_warnings.append(f"  [{acc['name']}]: {cash:.2f}元")
        
        if eggs >= EGG_WARNING_THRESHOLD:
            egg_warnings.append(f"  [{acc['name']}]: {eggs}个")
        
        for warning in acc.get('warnings', []):
            task_warnings[warning].append(acc['name'])
    
    # 生成报告文本
    report = f"📅 报告日期: {report_date}\n"
    report += f"👤 总账号数: {total_accounts}个\n"
    report += f"✅ 成功登录: {total_accounts}个\n"
    report += f"❌ 登录失败: 0个\n"
    report += f"🔄 处理中: 0个\n"
    report += f"💰 总金币量: {total_coins}金币\n"
    report += f"🥚 鸭蛋总数: {total_eggs}个\n"
    report += f"🌾 饲料总数: {total_feed}克\n"
    report += f"🎫  抽奖次数: {total_lottery_count}次\n"
    report += f"🎰 转盘总余额: {total_wheel_balance:.2f}元\n"
    report += f"📈 今日金币增加量: {total_coin_increment}金币\n"
    report += f"💵 总现金余额: {total_cash:.2f}元\n"
    report += f"💸 今日提现金额: {withdrawal:.2f}元\n\n"
    
    if cash_warnings:
        report += "💰 可提现超过阈值账号:\n"
        report += "\n".join(cash_warnings) + "\n\n"
    
    if egg_warnings:
        report += "🥚 鸭蛋可兑换超过阈值账号:\n"
        report += "\n".join(egg_warnings) + "\n\n"
    
    if task_warnings:
        report += "⚠️ 任务警告汇总:\n"
        for warning_type, accounts in task_warnings.items():
            report += f"⚠️ {warning_type}\n"
            for acc in accounts:
                report += f"    ⚠️ - 【{acc}】\n"
        report += "\n"
    
    # 账号详情
    report += "账号详情:\n"
    for acc_name, acc_data in today_accounts.items():
        coins = acc_data.get('coins', 0)
        cash = acc_data.get('cash', 0.0)
        eggs = acc_data.get('eggs', 0)
        feed = acc_data.get('feed', 0)
        lottery_count = acc_data.get('lottery_count', 0)
        wheel_balance = acc_data.get('wheel_balance', 0.0)
        
        # 获取昨日数据
        prev_acc = prev_data.get(acc_name, {})
        prev_cash = prev_acc.get('cash', 0.0)
        prev_coins = prev_acc.get('coins', 0)
        
        # 计算预期转换金额
        expected_conversion = prev_coins / 10000
        
        # 计算提现金额
        calculated_withdrawal = prev_cash + expected_conversion - cash
        
        # 计算金币增加量（更准确）
        coin_increment = get_account_coin_increment(acc_name, prev_coins, coins)
        
        report += f"🔷 [{acc_name}]\n"
        report += f"  日志文件: {acc_data.get('file', '未知')}\n"
        report += f"  💰 当前金币: {coins}\n"
        report += f"  💵 现金余额: {cash:.2f}元\n"
        report += f"  💸 今日提现: {max(0, calculated_withdrawal):.2f}元\n"
        report += f"  ℹ️ 提现检测: 昨日现金{prev_cash:.2f}元 + 金币转换{expected_conversion:.4f}元 - 今日现金{cash:.2f}元 = {calculated_withdrawal:.4f}元\n"
        report += f"  🥚 鸭蛋数: {eggs}个\n"
        report += f"  🌾 饲料数: {feed}克\n"
        report += f"  🎫  抽奖次数: {lottery_count}次\n"
        report += f"  🎰 转盘余额: {wheel_balance:.2f}元\n"
        report += f"  📈 今日金币增加量: +{coin_increment}金币\n"
        report += f"  🔄 昨日金币: {prev_coins} (转换金额: {expected_conversion:.4f}元)\n\n"
    
    return report

def get_latest_account_data(log_files, target_date):
    """获取指定日期的最新账号数据"""
    date_accounts = {}
    
    # 按修改时间排序（最新的文件最后处理）
    sorted_files = sorted(log_files, key=lambda x: os.path.getmtime(x))
    
    for log_file in sorted_files:
        file_date = os.path.basename(log_file)[:10]
        if file_date != target_date:
            continue
            
        if DEBUG_MODE:
            print(f"处理日志文件: {log_file} (修改时间: {datetime.datetime.fromtimestamp(os.path.getmtime(log_file))})")
        
        accounts = parse_log_file(log_file)
        for acc_name, acc_data in accounts.items():
            # 只保留每个账号的最新数据
            date_accounts[acc_name] = acc_data
    
    return date_accounts

def main():
    # 获取当前日期和昨天日期
    today = datetime.datetime.now().strftime("%Y-%m-%d")
    yesterday = (datetime.datetime.now() - datetime.timedelta(days=1)).strftime("%Y-%m-%d")
    
    # 查找所有日志文件
    log_dirs = glob.glob(LOG_DIR_PATTERN)
    all_log_files = []
    
    for log_dir in log_dirs:
        for file_name in os.listdir(log_dir):
            if file_name.endswith('.log'):
                file_path = os.path.join(log_dir, file_name)
                file_date = file_name[:10]
                # 只处理今天和昨天的日志
                if file_date in [today, yesterday]:
                    all_log_files.append(file_path)
    
    if DEBUG_MODE:
        print(f"找到日志文件: {all_log_files}")
    
    # 加载历史数据
    history_data = {}
    if os.path.exists(HISTORY_FILE):
        try:
            with open(HISTORY_FILE, 'r', encoding='utf-8') as f:
                history_data = json.load(f)
        except (json.JSONDecodeError, FileNotFoundError):
            history_data = {}
    
    # 获取今日最新账号数据（按文件修改时间排序）
    today_accounts = get_latest_account_data(all_log_files, today)
    
    # 获取昨日最新账号数据
    if yesterday in history_data:
        # 使用历史数据中的昨日数据
        yesterday_accounts = history_data[yesterday]
        if DEBUG_MODE:
            print(f"使用历史数据中的昨日账号数据")
    else:
        # 从日志文件中提取昨日数据
        yesterday_accounts = get_latest_account_data(all_log_files, yesterday)
        if DEBUG_MODE:
            print(f"从日志文件中提取昨日账号数据")
    
    # 更新历史数据（只存储最新状态）
    history_data[today] = today_accounts
    
    # 只保留最近三天的数据
    dates = sorted(history_data.keys(), reverse=True)
    for date in dates[3:]:
        del history_data[date]
    
    # 保存历史数据
    os.makedirs(os.path.dirname(HISTORY_FILE), exist_ok=True)
    with open(HISTORY_FILE, 'w', encoding='utf-8') as f:
        json.dump(history_data, f, ensure_ascii=False, indent=2)
    
    # 生成报告（使用昨日数据对比）
    report_content = generate_report(today_accounts, yesterday_accounts, today)
    
    # 保存报告
    os.makedirs(os.path.dirname(REPORT_FILE), exist_ok=True)
    with open(REPORT_FILE, 'w', encoding='utf-8') as f:
        f.write(report_content)
    
    # 发送PushPlus通知
    title = f"快手极速版每日报告 - {today}"
    message_id = pushplus_send(title, report_content)
    
    if DEBUG_MODE:
        print("报告生成完成:")
        print(report_content)
        
        if message_id:
            print(f"消息已发送，ID: {message_id}")

if __name__ == "__main__":
    main()